package com.zhouxiaoxuan13.promotionservice.service;

import com.zhouxiaoxuan13.promotionservice.entity.Promotion;
import com.zhouxiaoxuan13.promotionservice.dto.PromotionDetailDTO;
import com.zhouxiaoxuan13.promotionservice.repository.PromotionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class PromotionService {

    @Autowired
    private PromotionRepository promotionRepository;

    @Transactional(readOnly = true)
    public List<Promotion> getAllPromotions() {
        return promotionRepository.findAll();
    }

    @Transactional(readOnly = true)
    public List<PromotionDetailDTO> getAllPromotionsWithDetails() {
        List<Object[]> results = promotionRepository.findAllPromotionsWithProductDetailsNative();
        return convertToPromotionDetailDTOs(results);
    }

    @Transactional(readOnly = true)
    public Optional<Promotion> getPromotionById(Long id) {
        return promotionRepository.findById(id);
    }

    @Transactional(readOnly = true)
    public List<Promotion> getActivePromotions() {
        return promotionRepository.findCurrentlyActivePromotions();
    }

    @Transactional(readOnly = true)
    public List<PromotionDetailDTO> getActivePromotionsWithDetails() {
        List<Object[]> results = promotionRepository.findActivePromotionsWithProductDetailsNative();
        return convertToPromotionDetailDTOs(results);
    }

    @Transactional
    public Promotion createPromotion(Promotion promotion) {
        // 验证日期
        if (promotion.getEndDate().isBefore(promotion.getStartDate())) {
            throw new IllegalArgumentException("Promotion end date must be after start date.");
        }

        // 保存促销
        Promotion savedPromotion = promotionRepository.save(promotion);

        // 暂时禁用自动同步，等数据库修复后再启用
        // TODO: 实现价格同步逻辑

        return savedPromotion;
    }

    @Transactional
    public Optional<Promotion> updatePromotion(Long id, Promotion promotionDetails) {
        return promotionRepository.findById(id)
                .map(existingPromotion -> {
                    // 验证日期
                    if (promotionDetails.getEndDate() != null && promotionDetails.getStartDate() != null
                        && promotionDetails.getEndDate().isBefore(promotionDetails.getStartDate())) {
                        throw new IllegalArgumentException("Promotion end date must be after start date.");
                    }

                    // 更新字段
                    existingPromotion.setName(promotionDetails.getName());
                    existingPromotion.setDescription(promotionDetails.getDescription());
                    existingPromotion.setFreshProductId(promotionDetails.getFreshProductId());
                    existingPromotion.setPromotionPrice(promotionDetails.getPromotionPrice());
                    existingPromotion.setStartDate(promotionDetails.getStartDate());
                    existingPromotion.setEndDate(promotionDetails.getEndDate());
                    existingPromotion.setActive(promotionDetails.isActive());

                    // 保存促销
                    Promotion savedPromotion = promotionRepository.save(existingPromotion);

                    // 暂时禁用自动同步，等数据库修复后再启用
                    // TODO: 实现价格同步逻辑

                    return savedPromotion;
                });
    }

    @Transactional
    public boolean deletePromotion(Long id) {
        if (promotionRepository.existsById(id)) {
            // 暂时禁用自动同步，等数据库修复后再启用
            // TODO: 实现价格同步逻辑

            promotionRepository.deleteById(id);
            return true;
        }
        return false;
    }



    @Transactional(readOnly = true)
    public List<Promotion> searchPromotionsByName(String name) {
        return promotionRepository.findByNameContainingIgnoreCase(name);
    }

    // 同步促销价格到生鲜商品
    @Transactional
    public void syncPromotionPrices() {
        List<Promotion> activePromotions = getActivePromotions();
        System.out.println("开始同步 " + activePromotions.size() + " 个活跃促销");

        // 暂时禁用自动同步，等数据库修复后再启用
        // TODO: 实现价格同步逻辑
        for (Promotion promotion : activePromotions) {
            System.out.println("促销: " + promotion.getName() + " 商品ID: " + promotion.getFreshProductId());
        }

        System.out.println("所有活跃促销同步完成");
    }

    /**
     * 转换原生查询结果为PromotionDetailDTO列表
     */
    private List<PromotionDetailDTO> convertToPromotionDetailDTOs(List<Object[]> results) {
        List<PromotionDetailDTO> dtos = new ArrayList<>();

        for (Object[] row : results) {
            PromotionDetailDTO dto = new PromotionDetailDTO();

            // 促销信息 (索引 0-8)
            dto.setId(((Number) row[0]).longValue());
            dto.setName((String) row[1]);
            dto.setDescription((String) row[2]);
            dto.setPromotionPrice((BigDecimal) row[3]);
            dto.setStartDate(((Timestamp) row[4]).toLocalDateTime());
            dto.setEndDate(((Timestamp) row[5]).toLocalDateTime());
            dto.setActive((Boolean) row[6]);
            dto.setCreatedTime(row[7] != null ? ((Timestamp) row[7]).toLocalDateTime() : null);
            dto.setUpdatedTime(row[8] != null ? ((Timestamp) row[8]).toLocalDateTime() : null);

            // 商品信息 (索引 9-15)
            dto.setFreshProductId(((Number) row[9]).longValue());
            dto.setProductName((String) row[10]);
            dto.setProductDescription((String) row[11]);
            dto.setCategory((String) row[12]);
            dto.setSpecifications((String) row[13]);
            dto.setOriginalPrice((BigDecimal) row[14]);
            dto.setStockQuantity(row[15] != null ? ((Number) row[15]).intValue() : 0);

            dtos.add(dto);
        }

        return dtos;
    }
}
